package com.zj.juc.study.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName TicketDemo
 * @Description
 * @createTime 2024年12月23日 21:57
 */
public class TicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i <55 ; i++) {
                ticket.sale();
            }
        },"a").start();
        new Thread(()->{
            for (int i = 0; i <55 ; i++) {
                ticket.sale();
            }
        },"b").start();
        new Thread(()->{
            for (int i = 0; i <55 ; i++) {
                ticket.sale();
            }
        },"c").start();
    }
}
class Ticket{
    private int number = 50;

    //非公平锁
//    ReentrantLock reentrantLock  = new ReentrantLock();
    //公平锁
    ReentrantLock reentrantLock = new ReentrantLock(true);
    public void sale(){
        reentrantLock.lock();
        try {
            if (number > 0){
                System.out.println("["+Thread.currentThread().getName()+"]"+"sale ticket"+(number--)+",has ticket:"+number);
            }
        }finally {
            reentrantLock.unlock();
        }

    }
}